<?php

namespace login\model;

require_once("User.php");

class LoginDAL {
	/**
	 * [getUser description]
	 * @param  string $username 
	 * @param  mysqli $mysqli   
	 * @return \login\model\User
	 * @throws Exception om något går fel i databasen
	 */
	public static function getUser($username, \mysqli $mysqli) {
		$sqlQ = "SELECT `Username`, `PW` FROM `Users` WHERE `Username` = ?";

		$stmt = $mysqli->prepare($sqlQ);
		if ($stmt == false) {
			throw new \Exception("Prepare of sql question failed" . $this->mysqli->error);
		}

		$res = $stmt->bind_param("s", $username);
		if ($res == false) {
			throw new \Exception("Bind param failed " . $stmt->error);
		}

		$res = $stmt->execute();
		if($res == false) {
			throw new \Exception("Database execute failed " . $stmt->error);
		}

		$res = $stmt->bind_result($username, $password);
		if ($res == false) {
			throw new \Exception("Bind result failed " . $stmt->error);
		}

		if($stmt->fetch()) {
			return new User($username, $password);
		}
		throw new \Exception("Find no user");
	}

	public static function findUser($username, $mysqli) {
		try {
			self::getUser($username, $mysqli);
		} catch (\Exception $e) {
			return true;
		}
		return false;
	}
}